﻿Imports System
Imports System.Collections
Imports System.Collections.Generic
Imports System.ComponentModel
Imports System.ComponentModel.Design
Imports System.Diagnostics.CodeAnalysis
Imports System.Drawing
Imports System.Globalization
Imports System.Reflection
Imports System.Security.Permissions
Imports System.Text
Imports System.Windows.Forms
Imports System.Windows.Forms.Design
Imports System.Workflow.Activities.Rules
Imports System.Workflow.ComponentModel
Imports System.Workflow.ComponentModel.Compiler
Imports System.Workflow.ComponentModel.Design

Namespace System.Workflow.Activities.Rules.Design
    Public Class RuleSetDialog
        Inherits Form
        ' Methods
        Public Sub New(ByVal activity As Activity, ByVal ruleSet As RuleSet)
            Dim service As ITypeProvider
            Me.sortOrder = New Boolean(4  - 1) {}
            If (activity Is Nothing) Then
                Throw New ArgumentNullException("activity")
            End If
            Me.InitializeDialog(ruleSet)
            Me.serviceProvider = activity.Site
            If (Not Me.serviceProvider Is Nothing) Then
                service = DirectCast(Me.serviceProvider.GetService(GetType(ITypeProvider)), ITypeProvider)
                If (service Is Nothing) Then
                    Throw New InvalidOperationException(String.Format(CultureInfo.CurrentCulture, Messages.MissingService, New Object() { GetType(ITypeProvider).FullName }))
                End If
                Dim loader As WorkflowDesignerLoader = [TryCast](Me.serviceProvider.GetService(GetType(WorkflowDesignerLoader)),WorkflowDesignerLoader)
                If (Not loader Is Nothing) Then
                    loader.Flush
                End If
            Else
                Dim provider2 As New TypeProvider(Nothing)
                Dim assembly As Assembly
                For Each assembly In AppDomain.CurrentDomain.GetAssemblies
                    provider2.AddAssembly([assembly])
                Next
                service = provider2
            End If
            Dim validation As New RuleValidation(activity, service, False)
            Me.ruleParser = New Parser(validation)
        End Sub

        Public Sub New(ByVal activityType As Type, ByVal typeProvider As ITypeProvider, ByVal ruleSet As RuleSet)
            Me.sortOrder = New Boolean(4  - 1) {}
            If (activityType Is Nothing) Then
                Throw New ArgumentNullException("activityType")
            End If
            Me.InitializeDialog(ruleSet)
            Dim validation As New RuleValidation(activityType, typeProvider)
            Me.ruleParser = New Parser(validation)
        End Sub

        Private Sub activeCheckBox_CheckedChanged(ByVal sender As Object, ByVal e As EventArgs)
            If (Me.rulesListView.SelectedItems.Count > 0) Then
                Dim tag As Rule = [TryCast](Me.rulesListView.SelectedItems.Item(0).Tag,Rule)
                tag.Active = Me.activeCheckBox.Checked
                Me.UpdateItem(Me.rulesListView.SelectedItems.Item(0), tag)
            End If
        End Sub

        Private Function AddNewItem(ByVal rule As Rule) As ListViewItem
            Dim item As New ListViewItem(New String() { rule.Name, String.Empty, String.Empty, String.Empty, String.Empty })
            Me.rulesListView.Items.Add(item)
            item.Tag = rule
            Me.UpdateItem(item, rule)
            Return item
        End Function

        Private Sub buttonCancel_Click(ByVal sender As Object, ByVal e As EventArgs)
            RemoveHandler Me.conditionTextBox.Validating, New CancelEventHandler(AddressOf Me.conditionTextBox_Validating)
            RemoveHandler Me.thenTextBox.Validating, New CancelEventHandler(AddressOf Me.thenTextBox_Validating)
            RemoveHandler Me.elseTextBox.Validating, New CancelEventHandler(AddressOf Me.elseTextBox_Validating)
        End Sub

        Private Sub chainingBehaviourComboBox_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs)
            Me.dialogRuleSet.ChainingBehavior = DirectCast(Me.chainingBehaviourComboBox.SelectedIndex, RuleChainingBehavior)
        End Sub

        <SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")> _
        Private Sub conditionTextBox_Validating(ByVal sender As Object, ByVal e As CancelEventArgs)
            If (Me.rulesListView.SelectedItems.Count <> 0) Then
                Try 
                    Dim tag As Rule = [TryCast](Me.rulesListView.SelectedItems.Item(0).Tag,Rule)
                    Dim condition As RuleCondition = Me.ruleParser.ParseCondition(Me.conditionTextBox.Text)
                    tag.Condition = condition
                    If Not String.IsNullOrEmpty(Me.conditionTextBox.Text) Then
                        Me.conditionTextBox.Text = condition.ToString.Replace(ChrW(10), ChrW(13) & ChrW(10))
                    End If
                    Me.UpdateItem(Me.rulesListView.SelectedItems.Item(0), tag)
                    Me.conditionErrorProvider.SetError(Me.conditionTextBox, String.Empty)
                Catch exception As Exception
                    Me.conditionErrorProvider.SetError(Me.conditionTextBox, exception.Message)
                    DesignerHelpers.DisplayError((Messages.Error_ConditionParser & ChrW(10) & exception.Message), Me.Text, Me.serviceProvider)
                    e.Cancel = True
                End Try
            End If
        End Sub

        Private Function CreateNewName() As String
            Dim newRuleName As String = Messages.NewRuleName
            Dim num As Integer = 1
            Do While True
                Dim name As String = (newRuleName & num.ToString(CultureInfo.InvariantCulture))
                If Me.IsUniqueIdentifier(name) Then
                    Return name
                End If
                num += 1
            Loop
        End Function

        Private Sub deleteToolStripButton_Click(ByVal sender As Object, ByVal e As EventArgs)
            Dim activeControl As IntellisenseTextBox = [TryCast](MyBase.ActiveControl,IntellisenseTextBox)
            If (Not activeControl Is Nothing) Then
                activeControl.HideIntellisenceDropDown
            End If
            Dim options As MessageBoxOptions = 0
            If CultureInfo.CurrentUICulture.TextInfo.IsRightToLeft Then
                options = (MessageBoxOptions.RtlReading Or MessageBoxOptions.RightAlign)
            End If
            If (MessageBox.Show(Me, Messages.RuleConfirmDeleteMessageText, Messages.DeleteRule, MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1, options) = DialogResult.OK) Then
                Dim tag As Rule = [TryCast](Me.rulesListView.SelectedItems.Item(0).Tag,Rule)
                Dim index As Integer = Me.rulesListView.SelectedIndices.Item(0)
                Me.dialogRuleSet.Rules.Remove(tag)
                Me.rulesListView.Items.RemoveAt(index)
                If (Me.rulesListView.Items.Count > 0) Then
                    Dim num2 As Integer = Math.Min(index, (Me.rulesListView.Items.Count - 1))
                    Me.rulesListView.Items.Item(num2).Selected = True
                End If
            End If
        End Sub

        Protected Overrides Sub Dispose(ByVal disposing As Boolean)
            If (disposing AndAlso (Not Me.components Is Nothing)) Then
                Me.components.Dispose
            End If
            MyBase.Dispose(disposing)
        End Sub

        <SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")> _
        Private Sub elseTextBox_Validating(ByVal sender As Object, ByVal e As CancelEventArgs)
            If (Me.rulesListView.SelectedItems.Count <> 0) Then
                Try 
                    Dim tag As Rule = DirectCast(Me.rulesListView.SelectedItems.Item(0).Tag, Rule)
                    Dim actions As List([Of] RuleAction) = Me.ruleParser.ParseStatementList(Me.elseTextBox.Text)
                    Me.elseTextBox.Text = RuleSetDialog.GetActionsString(actions)
                    tag.ElseActions.Clear
                    Dim action As RuleAction
                    For Each action In actions
                        tag.ElseActions.Add(action)
                    Next
                    Me.UpdateItem(Me.rulesListView.SelectedItems.Item(0), tag)
                    Me.elseErrorProvider.SetError(Me.elseTextBox, String.Empty)
                Catch exception As Exception
                    Me.elseErrorProvider.SetError(Me.elseTextBox, exception.Message)
                    DesignerHelpers.DisplayError((Messages.Error_ActionsParser & ChrW(10) & exception.Message), Me.Text, Me.serviceProvider)
                    e.Cancel = True
                End Try
            End If
        End Sub

        Private Shared Function GetActionsString(ByVal actions As IList([Of] RuleAction)) As String
            If (actions Is Nothing) Then
                Throw New ArgumentNullException("actions")
            End If
            Dim flag As Boolean = True
            Dim builder As New StringBuilder
            Dim action As RuleAction
            For Each action In actions
                If Not flag Then
                    builder.Append(ChrW(13) & ChrW(10))
                Else
                    flag = False
                End If
                builder.Append(action.ToString)
            Next
            Return builder.ToString
        End Function

        Private Sub InitializeComponent()
            Me.components = New Container
            Dim manager As New ComponentResourceManager(GetType(RuleSetDialog))
            Me.nameColumnHeader = New ColumnHeader
            Me.rulesListView = New ListView
            Me.priorityColumnHeader = New ColumnHeader
            Me.reevaluationCountColumnHeader = New ColumnHeader
            Me.activeColumnHeader = New ColumnHeader
            Me.rulePreviewColumnHeader = New ColumnHeader
            Me.rulesGroupBox = New GroupBox
            Me.panel1 = New Panel
            Me.chainingLabel = New Label
            Me.chainingBehaviourComboBox = New ComboBox
            Me.rulesToolStrip = New ToolStrip
            Me.imageList = New ImageList(Me.components)
            Me.newRuleToolStripButton = New ToolStripButton
            Me.toolStripSeparator1 = New ToolStripSeparator
            Me.deleteToolStripButton = New ToolStripButton
            Me.buttonOK = New Button
            Me.ruleGroupBox = New GroupBox
            Me.reevaluationComboBox = New ComboBox
            Me.elseTextBox = New IntellisenseTextBox
            Me.elseLabel = New Label
            Me.thenTextBox = New IntellisenseTextBox
            Me.thenLabel = New Label
            Me.conditionTextBox = New IntellisenseTextBox
            Me.conditionLabel = New Label
            Me.nameTextBox = New TextBox
            Me.nameLabel = New Label
            Me.activeCheckBox = New CheckBox
            Me.reevaluationLabel = New Label
            Me.priorityTextBox = New TextBox
            Me.priorityLabel = New Label
            Me.buttonCancel = New Button
            Me.headerTextLabel = New Label
            Me.pictureBoxHeader = New PictureBox
            Me.okCancelTableLayoutPanel = New TableLayoutPanel
            Me.conditionErrorProvider = New ErrorProvider(Me.components)
            Me.thenErrorProvider = New ErrorProvider(Me.components)
            Me.elseErrorProvider = New ErrorProvider(Me.components)
            Me.rulesGroupBox.SuspendLayout
            Me.panel1.SuspendLayout
            Me.rulesToolStrip.SuspendLayout
            Me.ruleGroupBox.SuspendLayout
            DirectCast(Me.pictureBoxHeader, ISupportInitialize).BeginInit
            Me.okCancelTableLayoutPanel.SuspendLayout
            DirectCast(Me.conditionErrorProvider, ISupportInitialize).BeginInit
            DirectCast(Me.thenErrorProvider, ISupportInitialize).BeginInit
            DirectCast(Me.elseErrorProvider, ISupportInitialize).BeginInit
            MyBase.SuspendLayout
            Me.nameColumnHeader.Name = "nameColumnHeader"
            manager.ApplyResources(Me.nameColumnHeader, "nameColumnHeader")
            Me.rulesListView.Columns.AddRange(New ColumnHeader() { Me.nameColumnHeader, Me.priorityColumnHeader, Me.reevaluationCountColumnHeader, Me.activeColumnHeader, Me.rulePreviewColumnHeader })
            manager.ApplyResources(Me.rulesListView, "rulesListView")
            Me.rulesListView.FullRowSelect = True
            Me.rulesListView.HideSelection = False
            Me.rulesListView.MultiSelect = False
            Me.rulesListView.Name = "rulesListView"
            Me.rulesListView.UseCompatibleStateImageBehavior = False
            Me.rulesListView.View = View.Details
            AddHandler Me.rulesListView.SelectedIndexChanged, New EventHandler(AddressOf Me.rulesListView_SelectedIndexChanged)
            AddHandler Me.rulesListView.ColumnClick, New ColumnClickEventHandler(AddressOf Me.rulesListView_ColumnClick)
            manager.ApplyResources(Me.priorityColumnHeader, "priorityColumnHeader")
            manager.ApplyResources(Me.reevaluationCountColumnHeader, "reevaluationCountColumnHeader")
            manager.ApplyResources(Me.activeColumnHeader, "activeColumnHeader")
            manager.ApplyResources(Me.rulePreviewColumnHeader, "rulePreviewColumnHeader")
            Me.rulesGroupBox.Controls.Add(Me.panel1)
            manager.ApplyResources(Me.rulesGroupBox, "rulesGroupBox")
            Me.rulesGroupBox.Name = "rulesGroupBox"
            Me.rulesGroupBox.TabStop = False
            Me.panel1.Controls.Add(Me.chainingLabel)
            Me.panel1.Controls.Add(Me.chainingBehaviourComboBox)
            Me.panel1.Controls.Add(Me.rulesToolStrip)
            Me.panel1.Controls.Add(Me.rulesListView)
            manager.ApplyResources(Me.panel1, "panel1")
            Me.panel1.Name = "panel1"
            manager.ApplyResources(Me.chainingLabel, "chainingLabel")
            Me.chainingLabel.Name = "chainingLabel"
            Me.chainingBehaviourComboBox.DropDownStyle = ComboBoxStyle.DropDownList
            Me.chainingBehaviourComboBox.FormattingEnabled = True
            manager.ApplyResources(Me.chainingBehaviourComboBox, "chainingBehaviourComboBox")
            Me.chainingBehaviourComboBox.Name = "chainingBehaviourComboBox"
            AddHandler Me.chainingBehaviourComboBox.SelectedIndexChanged, New EventHandler(AddressOf Me.chainingBehaviourComboBox_SelectedIndexChanged)
            Me.rulesToolStrip.BackColor = SystemColors.Control
            Me.rulesToolStrip.GripStyle = ToolStripGripStyle.Hidden
            Me.rulesToolStrip.ImageList = Me.imageList
            Me.rulesToolStrip.Items.AddRange(New ToolStripItem() { Me.newRuleToolStripButton, Me.toolStripSeparator1, Me.deleteToolStripButton })
            manager.ApplyResources(Me.rulesToolStrip, "rulesToolStrip")
            Me.rulesToolStrip.Name = "rulesToolStrip"
            Me.rulesToolStrip.RenderMode = ToolStripRenderMode.System
            Me.rulesToolStrip.TabStop = True
            Me.imageList.ImageStream = DirectCast(manager.GetObject("imageList.ImageStream"), ImageListStreamer)
            Me.imageList.TransparentColor = Color.Transparent
            Me.imageList.Images.SetKeyName(0, "NewRule.bmp")
            Me.imageList.Images.SetKeyName(1, "RenameRule.bmp")
            Me.imageList.Images.SetKeyName(2, "Delete.bmp")
            manager.ApplyResources(Me.newRuleToolStripButton, "newRuleToolStripButton")
            Me.newRuleToolStripButton.Name = "newRuleToolStripButton"
            AddHandler Me.newRuleToolStripButton.Click, New EventHandler(AddressOf Me.newRuleToolStripButton_Click)
            Me.toolStripSeparator1.Name = "toolStripSeparator1"
            manager.ApplyResources(Me.toolStripSeparator1, "toolStripSeparator1")
            manager.ApplyResources(Me.deleteToolStripButton, "deleteToolStripButton")
            Me.deleteToolStripButton.Name = "deleteToolStripButton"
            AddHandler Me.deleteToolStripButton.Click, New EventHandler(AddressOf Me.deleteToolStripButton_Click)
            manager.ApplyResources(Me.buttonOK, "buttonOK")
            Me.buttonOK.DialogResult = DialogResult.OK
            Me.buttonOK.Name = "buttonOK"
            Me.ruleGroupBox.Controls.Add(Me.reevaluationComboBox)
            Me.ruleGroupBox.Controls.Add(Me.elseTextBox)
            Me.ruleGroupBox.Controls.Add(Me.elseLabel)
            Me.ruleGroupBox.Controls.Add(Me.thenTextBox)
            Me.ruleGroupBox.Controls.Add(Me.thenLabel)
            Me.ruleGroupBox.Controls.Add(Me.conditionTextBox)
            Me.ruleGroupBox.Controls.Add(Me.conditionLabel)
            Me.ruleGroupBox.Controls.Add(Me.nameTextBox)
            Me.ruleGroupBox.Controls.Add(Me.nameLabel)
            Me.ruleGroupBox.Controls.Add(Me.activeCheckBox)
            Me.ruleGroupBox.Controls.Add(Me.reevaluationLabel)
            Me.ruleGroupBox.Controls.Add(Me.priorityTextBox)
            Me.ruleGroupBox.Controls.Add(Me.priorityLabel)
            manager.ApplyResources(Me.ruleGroupBox, "ruleGroupBox")
            Me.ruleGroupBox.Name = "ruleGroupBox"
            Me.ruleGroupBox.TabStop = False
            Me.reevaluationComboBox.DropDownStyle = ComboBoxStyle.DropDownList
            Me.reevaluationComboBox.FormattingEnabled = True
            manager.ApplyResources(Me.reevaluationComboBox, "reevaluationComboBox")
            Me.reevaluationComboBox.Name = "reevaluationComboBox"
            AddHandler Me.reevaluationComboBox.SelectedIndexChanged, New EventHandler(AddressOf Me.reevaluationComboBox_SelectedIndexChanged)
            Me.elseTextBox.AcceptsReturn = True
            manager.ApplyResources(Me.elseTextBox, "elseTextBox")
            Me.elseTextBox.Name = "elseTextBox"
            AddHandler Me.elseTextBox.Validating, New CancelEventHandler(AddressOf Me.elseTextBox_Validating)
            manager.ApplyResources(Me.elseLabel, "elseLabel")
            Me.elseLabel.Name = "elseLabel"
            Me.thenTextBox.AcceptsReturn = True
            manager.ApplyResources(Me.thenTextBox, "thenTextBox")
            Me.thenTextBox.Name = "thenTextBox"
            AddHandler Me.thenTextBox.Validating, New CancelEventHandler(AddressOf Me.thenTextBox_Validating)
            manager.ApplyResources(Me.thenLabel, "thenLabel")
            Me.thenLabel.Name = "thenLabel"
            Me.conditionTextBox.AcceptsReturn = True
            manager.ApplyResources(Me.conditionTextBox, "conditionTextBox")
            Me.conditionTextBox.Name = "conditionTextBox"
            AddHandler Me.conditionTextBox.Validating, New CancelEventHandler(AddressOf Me.conditionTextBox_Validating)
            manager.ApplyResources(Me.conditionLabel, "conditionLabel")
            Me.conditionLabel.Name = "conditionLabel"
            manager.ApplyResources(Me.nameTextBox, "nameTextBox")
            Me.nameTextBox.Name = "nameTextBox"
            AddHandler Me.nameTextBox.Validating, New CancelEventHandler(AddressOf Me.nameTextBox_Validating)
            manager.ApplyResources(Me.nameLabel, "nameLabel")
            Me.nameLabel.Name = "nameLabel"
            manager.ApplyResources(Me.activeCheckBox, "activeCheckBox")
            Me.activeCheckBox.Name = "activeCheckBox"
            AddHandler Me.activeCheckBox.CheckedChanged, New EventHandler(AddressOf Me.activeCheckBox_CheckedChanged)
            manager.ApplyResources(Me.reevaluationLabel, "reevaluationLabel")
            Me.reevaluationLabel.Name = "reevaluationLabel"
            manager.ApplyResources(Me.priorityTextBox, "priorityTextBox")
            Me.priorityTextBox.Name = "priorityTextBox"
            AddHandler Me.priorityTextBox.Validating, New CancelEventHandler(AddressOf Me.priorityTextBox_Validating)
            manager.ApplyResources(Me.priorityLabel, "priorityLabel")
            Me.priorityLabel.Name = "priorityLabel"
            manager.ApplyResources(Me.buttonCancel, "buttonCancel")
            Me.buttonCancel.CausesValidation = False
            Me.buttonCancel.DialogResult = DialogResult.Cancel
            Me.buttonCancel.Name = "buttonCancel"
            AddHandler Me.buttonCancel.Click, New EventHandler(AddressOf Me.buttonCancel_Click)
            manager.ApplyResources(Me.headerTextLabel, "headerTextLabel")
            Me.headerTextLabel.Name = "headerTextLabel"
            manager.ApplyResources(Me.pictureBoxHeader, "pictureBoxHeader")
            Me.pictureBoxHeader.Name = "pictureBoxHeader"
            Me.pictureBoxHeader.TabStop = False
            manager.ApplyResources(Me.okCancelTableLayoutPanel, "okCancelTableLayoutPanel")
            Me.okCancelTableLayoutPanel.CausesValidation = False
            Me.okCancelTableLayoutPanel.Controls.Add(Me.buttonOK, 0, 0)
            Me.okCancelTableLayoutPanel.Controls.Add(Me.buttonCancel, 1, 0)
            Me.okCancelTableLayoutPanel.Name = "okCancelTableLayoutPanel"
            Me.conditionErrorProvider.BlinkStyle = ErrorBlinkStyle.NeverBlink
            Me.conditionErrorProvider.ContainerControl = Me
            Me.thenErrorProvider.BlinkStyle = ErrorBlinkStyle.NeverBlink
            Me.thenErrorProvider.ContainerControl = Me
            Me.elseErrorProvider.BlinkStyle = ErrorBlinkStyle.NeverBlink
            Me.elseErrorProvider.ContainerControl = Me
            MyBase.AcceptButton = Me.buttonOK
            manager.ApplyResources(Me, "$this")
            MyBase.AutoScaleMode = AutoScaleMode.Font
            MyBase.CancelButton = Me.buttonCancel
            MyBase.Controls.Add(Me.ruleGroupBox)
            MyBase.Controls.Add(Me.headerTextLabel)
            MyBase.Controls.Add(Me.pictureBoxHeader)
            MyBase.Controls.Add(Me.okCancelTableLayoutPanel)
            MyBase.Controls.Add(Me.rulesGroupBox)
            MyBase.FormBorderStyle = FormBorderStyle.FixedDialog
            MyBase.HelpButton = True
            MyBase.MaximizeBox = False
            MyBase.MinimizeBox = False
            MyBase.Name = "RuleSetDialog"
            MyBase.ShowInTaskbar = False
            MyBase.SizeGripStyle = SizeGripStyle.Hide
            Me.rulesGroupBox.ResumeLayout(False)
            Me.panel1.ResumeLayout(False)
            Me.panel1.PerformLayout
            Me.rulesToolStrip.ResumeLayout(False)
            Me.rulesToolStrip.PerformLayout
            Me.ruleGroupBox.ResumeLayout(False)
            Me.ruleGroupBox.PerformLayout
            DirectCast(Me.pictureBoxHeader, ISupportInitialize).EndInit
            Me.okCancelTableLayoutPanel.ResumeLayout(False)
            Me.okCancelTableLayoutPanel.PerformLayout
            DirectCast(Me.conditionErrorProvider, ISupportInitialize).EndInit
            DirectCast(Me.thenErrorProvider, ISupportInitialize).EndInit
            DirectCast(Me.elseErrorProvider, ISupportInitialize).EndInit
            MyBase.ResumeLayout(False)
            MyBase.PerformLayout
        End Sub

        Private Sub InitializeDialog(ByVal ruleSet As RuleSet)
            Me.InitializeComponent
            AddHandler Me.conditionTextBox.PopulateAutoCompleteList, New EventHandler([Of] AutoCompletionEventArgs)(AddressOf Me.PopulateAutoCompleteList)
            AddHandler Me.thenTextBox.PopulateAutoCompleteList, New EventHandler([Of] AutoCompletionEventArgs)(AddressOf Me.PopulateAutoCompleteList)
            AddHandler Me.elseTextBox.PopulateAutoCompleteList, New EventHandler([Of] AutoCompletionEventArgs)(AddressOf Me.PopulateAutoCompleteList)
            AddHandler Me.conditionTextBox.PopulateToolTipList, New EventHandler([Of] AutoCompletionEventArgs)(AddressOf Me.PopulateAutoCompleteList)
            AddHandler Me.thenTextBox.PopulateToolTipList, New EventHandler([Of] AutoCompletionEventArgs)(AddressOf Me.PopulateAutoCompleteList)
            AddHandler Me.elseTextBox.PopulateToolTipList, New EventHandler([Of] AutoCompletionEventArgs)(AddressOf Me.PopulateAutoCompleteList)
            Me.reevaluationComboBox.Items.Add(Messages.ReevaluationNever)
            Me.reevaluationComboBox.Items.Add(Messages.ReevaluationAlways)
            Me.chainingBehaviourComboBox.Items.Add(Messages.Sequential)
            Me.chainingBehaviourComboBox.Items.Add(Messages.ExplicitUpdateOnly)
            Me.chainingBehaviourComboBox.Items.Add(Messages.FullChaining)
            AddHandler MyBase.HelpRequested, New HelpEventHandler(AddressOf Me.OnHelpRequested)
            AddHandler MyBase.HelpButtonClicked, New CancelEventHandler(AddressOf Me.OnHelpClicked)
            If (Not ruleSet Is Nothing) Then
                Me.dialogRuleSet = ruleSet.Clone
            Else
                Me.dialogRuleSet = New RuleSet
            End If
            Me.chainingBehaviourComboBox.SelectedIndex = CInt(Me.dialogRuleSet.ChainingBehavior)
            Me.rulesListView.Select
            Dim rule As Rule
            For Each rule In Me.dialogRuleSet.Rules
                Me.AddNewItem(rule)
            Next
            If (Me.rulesListView.Items.Count > 0) Then
                Me.rulesListView.Items.Item(0).Selected = True
            Else
                Me.rulesListView_SelectedIndexChanged(Me, New EventArgs)
            End If
        End Sub

        Private Function IsUniqueIdentifier(ByVal name As String) As Boolean
            Dim rule As Rule
            For Each rule In Me.dialogRuleSet.Rules
                If (rule.Name = name) Then
                    Return False
                End If
            Next
            Return True
        End Function

        Private Sub nameTextBox_Validating(ByVal sender As Object, ByVal e As CancelEventArgs)
            If (Me.rulesListView.SelectedItems.Count > 0) Then
                Dim tag As Rule = [TryCast](Me.rulesListView.SelectedItems.Item(0).Tag,Rule)
                If (Me.nameTextBox.Text <> tag.Name) Then
                    Dim text As String = Me.nameTextBox.Text
                    If String.IsNullOrEmpty([text]) Then
                        e.Cancel = True
                        DesignerHelpers.DisplayError(Messages.Error_RuleNameIsEmpty, Me.Text, Me.serviceProvider)
                    ElseIf (tag.Name = [text]) Then
                        Me.nameTextBox.Text = [text]
                    ElseIf Not Me.IsUniqueIdentifier([text]) Then
                        e.Cancel = True
                        DesignerHelpers.DisplayError(Messages.Error_DuplicateRuleName, Me.Text, Me.serviceProvider)
                    Else
                        tag.Name = [text]
                        Me.UpdateItem(Me.rulesListView.SelectedItems.Item(0), tag)
                    End If
                End If
            End If
        End Sub

        Private Sub newRuleToolStripButton_Click(ByVal sender As Object, ByVal e As EventArgs)
            If Me.rulesToolStrip.Focus Then
                Dim rule As New Rule { _
                    .Name = Me.CreateNewName _
                }
                Me.dialogRuleSet.Rules.Add(rule)
                Dim item As ListViewItem = Me.AddNewItem(rule)
                item.Selected = True
                item.Focused = True
                Dim index As Integer = Me.rulesListView.Items.IndexOf(item)
                Me.rulesListView.EnsureVisible(index)
            End If
        End Sub

        Private Sub OnHelpClicked(ByVal sender As Object, ByVal e As CancelEventArgs)
            e.Cancel = True
            Me.ShowHelp
        End Sub

        Private Sub OnHelpRequested(ByVal sender As Object, ByVal e As HelpEventArgs)
            Me.ShowHelp
        End Sub

        Private Sub PopulateAutoCompleteList(ByVal sender As Object, ByVal e As AutoCompletionEventArgs)
            e.AutoCompleteValues = Me.ruleParser.GetExpressionCompletions(e.Prefix)
        End Sub

        <SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")> _
        Private Sub priorityTextBox_Validating(ByVal sender As Object, ByVal e As CancelEventArgs)
            If (Me.rulesListView.SelectedItems.Count > 0) Then
                Dim tag As Rule = [TryCast](Me.rulesListView.SelectedItems.Item(0).Tag,Rule)
                Try 
                    tag.Priority = Integer.Parse(Me.priorityTextBox.Text, CultureInfo.CurrentCulture)
                    Me.UpdateItem(Me.rulesListView.SelectedItems.Item(0), tag)
                Catch obj1 As Object
                    e.Cancel = True
                    DesignerHelpers.DisplayError(Messages.Error_InvalidPriority, Me.Text, Me.serviceProvider)
                End Try
            End If
        End Sub

        <SecurityPermission(SecurityAction.LinkDemand, Flags:=SecurityPermissionFlag.UnmanagedCode)> _
        Protected Overrides Function ProcessCmdKey(ByRef msg As Message, ByVal keyData As Keys) As Boolean
            If keyData.Equals(Keys.Escape) Then
                RemoveHandler Me.conditionTextBox.Validating, New CancelEventHandler(AddressOf Me.conditionTextBox_Validating)
                RemoveHandler Me.thenTextBox.Validating, New CancelEventHandler(AddressOf Me.thenTextBox_Validating)
                RemoveHandler Me.elseTextBox.Validating, New CancelEventHandler(AddressOf Me.elseTextBox_Validating)
            End If
            Return MyBase.ProcessCmdKey((msg), keyData)
        End Function

        Private Sub reevaluationComboBox_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs)
            If (Me.rulesListView.SelectedItems.Count > 0) Then
                Dim tag As Rule = [TryCast](Me.rulesListView.SelectedItems.Item(0).Tag,Rule)
                tag.ReevaluationBehavior = DirectCast(Me.reevaluationComboBox.SelectedIndex, RuleReevaluationBehavior)
                Me.UpdateItem(Me.rulesListView.SelectedItems.Item(0), tag)
            End If
        End Sub

        Private Sub rulesListView_ColumnClick(ByVal sender As Object, ByVal e As ColumnClickEventArgs)
            If (e.Column < 4) Then
                Me.rulesListView.ListViewItemSorter = New ListViewItemComparer(e.Column, Me.sortOrder(e.Column))
                Me.sortOrder(e.Column) = Not Me.sortOrder(e.Column)
            End If
        End Sub

        Private Sub rulesListView_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs)
            If (Me.rulesListView.SelectedItems.Count > 0) Then
                Dim tag As Rule = [TryCast](Me.rulesListView.SelectedItems.Item(0).Tag,Rule)
                Me.nameTextBox.Enabled = True
                Me.activeCheckBox.Enabled = True
                Me.reevaluationComboBox.Enabled = True
                Me.priorityTextBox.Enabled = True
                Me.conditionTextBox.Enabled = True
                Me.thenTextBox.Enabled = True
                Me.elseTextBox.Enabled = True
                Me.nameTextBox.Text = tag.Name
                Me.activeCheckBox.Checked = tag.Active
                Me.reevaluationComboBox.SelectedIndex = CInt(tag.ReevaluationBehavior)
                Me.priorityTextBox.Text = tag.Priority.ToString(CultureInfo.CurrentCulture)
                Me.conditionTextBox.Text = If((Not tag.Condition Is Nothing), tag.Condition.ToString.Replace(ChrW(10), ChrW(13) & ChrW(10)), String.Empty)
                Try 
                    Me.ruleParser.ParseCondition(Me.conditionTextBox.Text)
                    Me.conditionErrorProvider.SetError(Me.conditionTextBox, String.Empty)
                Catch exception As RuleSyntaxException
                    Me.conditionErrorProvider.SetError(Me.conditionTextBox, exception.Message)
                End Try
                Me.thenTextBox.Text = RuleSetDialog.GetActionsString(tag.ThenActions)
                Try 
                    Me.ruleParser.ParseStatementList(Me.thenTextBox.Text)
                    Me.thenErrorProvider.SetError(Me.thenTextBox, String.Empty)
                Catch exception2 As RuleSyntaxException
                    Me.thenErrorProvider.SetError(Me.thenTextBox, exception2.Message)
                End Try
                Me.elseTextBox.Text = RuleSetDialog.GetActionsString(tag.ElseActions)
                Try 
                    Me.ruleParser.ParseStatementList(Me.elseTextBox.Text)
                    Me.elseErrorProvider.SetError(Me.elseTextBox, String.Empty)
                Catch exception3 As RuleSyntaxException
                    Me.elseErrorProvider.SetError(Me.elseTextBox, exception3.Message)
                End Try
                Me.deleteToolStripButton.Enabled = True
            Else
                Me.nameTextBox.Text = String.Empty
                Me.activeCheckBox.Checked = False
                Me.reevaluationComboBox.Text = String.Empty
                Me.priorityTextBox.Text = String.Empty
                Me.conditionTextBox.Text = String.Empty
                Me.thenTextBox.Text = String.Empty
                Me.elseTextBox.Text = String.Empty
                Me.nameTextBox.Enabled = False
                Me.activeCheckBox.Enabled = False
                Me.reevaluationComboBox.Enabled = False
                Me.priorityTextBox.Enabled = False
                Me.conditionTextBox.Enabled = False
                Me.thenTextBox.Enabled = False
                Me.elseTextBox.Enabled = False
                Me.conditionErrorProvider.SetError(Me.conditionTextBox, String.Empty)
                Me.thenErrorProvider.SetError(Me.thenTextBox, String.Empty)
                Me.elseErrorProvider.SetError(Me.elseTextBox, String.Empty)
                Me.deleteToolStripButton.Enabled = False
            End If
        End Sub

        Private Shared Sub SetCaretAt(ByVal textBox As TextBoxBase, ByVal position As Integer)
            textBox.Focus
            textBox.SelectionStart = position
            textBox.SelectionLength = 0
            textBox.ScrollToCaret
        End Sub

        Private Sub ShowHelp()
            If (Not Me.serviceProvider Is Nothing) Then
                Dim service As IHelpService = [TryCast](Me.serviceProvider.GetService(GetType(IHelpService)),IHelpService)
                If (Not service Is Nothing) Then
                    service.ShowHelpFromKeyword((MyBase.GetType.FullName & ".UI"))
                Else
                    Dim service2 As IUIService = [TryCast](Me.serviceProvider.GetService(GetType(IUIService)),IUIService)
                    If (Not service2 Is Nothing) Then
                        service2.ShowError(Messages.NoHelp)
                    End If
                End If
            Else
                Dim service3 As IUIService = DirectCast(Me.GetService(GetType(IUIService)), IUIService)
                If (Not service3 Is Nothing) Then
                    service3.ShowError(Messages.NoHelp)
                End If
            End If
        End Sub

        <SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")> _
        Private Sub thenTextBox_Validating(ByVal sender As Object, ByVal e As CancelEventArgs)
            If (Me.rulesListView.SelectedItems.Count <> 0) Then
                Try 
                    Dim tag As Rule = [TryCast](Me.rulesListView.SelectedItems.Item(0).Tag,Rule)
                    Dim actions As List([Of] RuleAction) = Me.ruleParser.ParseStatementList(Me.thenTextBox.Text)
                    Me.thenTextBox.Text = RuleSetDialog.GetActionsString(actions)
                    tag.ThenActions.Clear
                    Dim action As RuleAction
                    For Each action In actions
                        tag.ThenActions.Add(action)
                    Next
                    Me.UpdateItem(Me.rulesListView.SelectedItems.Item(0), tag)
                    Me.thenErrorProvider.SetError(Me.thenTextBox, String.Empty)
                Catch exception As Exception
                    Me.thenErrorProvider.SetError(Me.thenTextBox, exception.Message)
                    DesignerHelpers.DisplayError((Messages.Error_ActionsParser & ChrW(10) & exception.Message), Me.Text, Me.serviceProvider)
                    e.Cancel = True
                End Try
            End If
        End Sub

        Private Sub UpdateItem(ByVal listViewItem As ListViewItem, ByVal rule As Rule)
            listViewItem.SubItems.Item(0).Text = rule.Name
            listViewItem.SubItems.Item(1).Text = rule.Priority.ToString(CultureInfo.CurrentCulture)
            listViewItem.SubItems.Item(2).Text = CStr(Me.reevaluationComboBox.Items.Item(CInt(rule.ReevaluationBehavior)))
            listViewItem.SubItems.Item(3).Text = rule.Active.ToString(CultureInfo.CurrentCulture)
            listViewItem.SubItems.Item(4).Text = DesignerHelpers.GetRulePreview(rule)
        End Sub


        ' Properties
        Public ReadOnly Property RuleSet As RuleSet
            Get
                Return Me.dialogRuleSet
            End Get
        End Property


        ' Fields
        Private activeCheckBox As CheckBox
        Private activeColumnHeader As ColumnHeader
        Private buttonCancel As Button
        Private buttonOK As Button
        Private chainingBehaviourComboBox As ComboBox
        Private chainingLabel As Label
        Private components As IContainer
        Private conditionErrorProvider As ErrorProvider
        Private conditionLabel As Label
        Private conditionTextBox As IntellisenseTextBox
        Private deleteToolStripButton As ToolStripButton
        Private dialogRuleSet As RuleSet
        Private elseErrorProvider As ErrorProvider
        Private elseLabel As Label
        Private elseTextBox As IntellisenseTextBox
        Private headerTextLabel As Label
        Private imageList As ImageList
        Private nameColumnHeader As ColumnHeader
        Private nameLabel As Label
        Private nameTextBox As TextBox
        Private newRuleToolStripButton As ToolStripButton
        Private Const numCols As Integer = 4
        Private okCancelTableLayoutPanel As TableLayoutPanel
        Private panel1 As Panel
        Private pictureBoxHeader As PictureBox
        Private priorityColumnHeader As ColumnHeader
        Private priorityLabel As Label
        Private priorityTextBox As TextBox
        Private reevaluationComboBox As ComboBox
        Private reevaluationCountColumnHeader As ColumnHeader
        Private reevaluationLabel As Label
        Private ruleGroupBox As GroupBox
        Private ruleParser As Parser
        Private rulePreviewColumnHeader As ColumnHeader
        Private rulesGroupBox As GroupBox
        Private rulesListView As ListView
        Private rulesToolStrip As ToolStrip
        Private serviceProvider As IServiceProvider
        Private sortOrder As Boolean()
        Private thenErrorProvider As ErrorProvider
        Private thenLabel As Label
        Private thenTextBox As IntellisenseTextBox
        Private toolStripSeparator1 As ToolStripSeparator

        ' Nested Types
        Private Class ListViewItemComparer
            Implements IComparer
            ' Methods
            Public Sub New(ByVal column As Integer, ByVal ascending As Boolean)
                Me.col = column
                Me.ascending = ascending
            End Sub

            Public Function [Compare](ByVal x As Object, ByVal y As Object) As Integer
                Dim num As Integer = 0
                Dim item As ListViewItem = DirectCast(x, ListViewItem)
                Dim item2 As ListViewItem = DirectCast(y, ListViewItem)
                If (Me.col = 1) Then
                    Dim result As Integer = 0
                    Dim num3 As Integer = 0
                    Integer.TryParse(item.SubItems.Item(Me.col).Text, NumberStyles.Integer, CultureInfo.CurrentCulture, result)
                    Integer.TryParse(item2.SubItems.Item(Me.col).Text, NumberStyles.Integer, CultureInfo.CurrentCulture, num3)
                    If (result <> num3) Then
                        num = (num3 - result)
                    Else
                        num = String.Compare(item.SubItems.Item(0).Text, item2.SubItems.Item(0).Text, StringComparison.CurrentCulture)
                    End If
                Else
                    num = String.Compare(item.SubItems.Item(Me.col).Text, item2.SubItems.Item(Me.col).Text, StringComparison.CurrentCulture)
                End If
                If Not Me.ascending Then
                    Return -num
                End If
                Return num
            End Function


            ' Fields
            Private ascending As Boolean
            Private col As Integer
        End Class
    End Class
End Namespace

